# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet1.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--cp", default = "", type = "character", help = "compare info "),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

groups <- unlist(strsplit(opt$cp, "_vs_"))
groups

data <- read_csv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Class"))

infoData <- read_csv(opt$i) %>%
  select(c(Class:Metabolite))

classes <- infoData %>%
  .$Class
uniqueClass <- unique(classes)
isScale <- if (length(uniqueClass) >= 2 & ("Reaction Ratio" %in% uniqueClass)) { TRUE } else FALSE

tData <- data %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value")
scaleData <- tData
if (isScale) {
  scaleData <- data %>%
    rowwise() %>%
    do({
      result <- as_tibble(.)
      data <- result %>%
        select(-"Metabolite") %>%
        unlist()
      var <- var(data)
      if (var == 0) {
        result %>% filter(FALSE)
      }else result
    }) %>%
    ungroup() %>%
    gather("SampleID", "Value", -Metabolite) %>%
    spread(Metabolite, "Value") %>%
    mutate_at(vars(-c("SampleID")), scale)
}

scaleData <- scaleData %>%
  gather("Metabolite", "Value", -SampleID) %>%
  spread(SampleID, "Value")

outData <- infoData %>%
  left_join(scaleData, by = "Metabolite")

write_csv(outData, "scale_data.csv")

mustScaleData <- data %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    data <- result %>%
      select(-"Metabolite") %>%
      unlist()
    var <- var(data)
    print(data)
    print(var)
    if (var == 0) {
      result %>% filter(FALSE)
    }else result
  }) %>%
  ungroup() %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  mutate_at(vars(-c("SampleID")), scale) %>%
  gather("Metabolite", "Value", -SampleID) %>%
  spread(SampleID, "Value")

mustScaleData


mustOutData <- infoData %>%
  right_join(mustScaleData, by = "Metabolite")

print(mustOutData %>% filter(Metabolite %in% c("muro_cholic acid", "Taurolithocholic acid")))


write_csv(mustOutData, "must_scale_data.csv")






